package array.binarysearch;

/**
 * @ClassName SearchInsert
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-09 20:19
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class SearchInsert {

    /**
     * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
     * <p>
     * 你可以假设数组中无重复元素。
     * <p>
     * 示例 1:
     * <p>
     * 输入: [1,3,5,6], 5
     * 输出: 2
     * 示例 2:
     * <p>
     * 输入: [1,3,5,6], 2
     * 输出: 1
     * 示例 3:
     * <p>
     * 输入: [1,3,5,6], 7
     * 输出: 4
     * 示例 4:
     * <p>
     * 输入: [1,3,5,6], 0
     * 输出：0
     *
     * 1,3,5,6 -- 2
     * left = 0 right =3 mid =1 nums[mid] = 3
     * left = 0 right = 0 mid = 0 nums[mid] = 1
     * left = 1 right = 0 return ;
     *
     * 1,3,5,6 -- 7
     * left = 0 ,right = 3 mid = 1 nums[mid] = 3
     * left = 2,right = 3 mid = 2 nums[mid] = 5
     * left = 3 right = 3 mid = 3 nums[mid] = 6
     * left = 4 right = 3 return ;
     *
     * 1,3,5,6  -- 0
     *
     * left = 0 ,right = 3, mid = 1 nums[mid]=3
     * left = 0 ,right = 0 mid = 0 nums[mid]=1
     * left = 0 ,right = -1 return ;
     * @param nums
     * @param target
     * @return
     */
    public int searchInsert(int[] nums, int target) {

        int left = 0, right = nums.length - 1;

        while (left <= right) {

            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            }
        }
        return right + 1;
    }
}